package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IProductGropMemberService;
import com.wondertek.poms.core.service.IProductGroupService;
import com.wondertek.poms.dao.po.ProductGroup;
import com.wondertek.poms.dao.pojo.ProductGroupExcelPojo;
import com.wondertek.poms.dao.pojo.ProductGroupPojo;
import com.wondertek.poms.service.vo.ProductGroupVo;
import io.swagger.annotations.Api;
import org.apache.commons.collections.ArrayStack;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@Api(value = "ProductGroupController", description = "产品组管理")
@RestController
@RequestMapping(value = "/productGroup")
public class ProductGroupController {

    @Autowired
    private IProductGroupService productGroupService;
    @Autowired
    private IProductGropMemberService productGropMemberService;

    @GetMapping(value = "/list")
    @ResponseBody
    public ResultBean list(ProductGroupVo productGroupVo,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "updateTime") String sidx,
                           @RequestParam(defaultValue = "desc") String sord){
        ProductGroupPojo productGroupPojo=new ProductGroupPojo();
        BeanUtils.copyProperties(productGroupVo,productGroupPojo);
        Page<ProductGroupPojo> list=productGroupService.findAll(productGroupPojo,page,rows,sord,sidx);
        return PageBean.ok(list.getTotalPages(),list.getTotalElements(),list.getContent());
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public ResultBean add(@RequestBody ProductGroupVo productGroupVo){
        List<String> messageList = ValidateFilter.getFilterMessage(productGroupVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }
        if(isRepeat(productGroupVo)){
            return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
        }
        ProductGroupPojo productGroupPojo=new ProductGroupPojo();
        BeanUtils.copyProperties(productGroupVo,productGroupPojo);
        ProductGroup productGroup=productGroupService.saveProductGroup(productGroupPojo);
        return ResultBean.ok(productGroup);
    }

    @DeleteMapping(value = "/delete")
    @ResponseBody
    public ResultBean delete(String ids){
        if (StrUtil.isBlank(ids)) {
            return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
        }
        String[] idArray = ids.split(",|，");
        for(String id:idArray){
            productGroupService.deleteById(Convert.toLong(id));
            productGropMemberService.deleteByGroupId(Convert.toLong(id));
        }
        return ResultBean.ok();
    }

    @GetMapping(value = "/get")
    @ResponseBody
    public ResultBean get(Long id){
        if (id == null) {
            return ResultBean.error(MessageCodes.get(MessageCodes.M980021));
        }
        ProductGroupPojo productGroupPojo=productGroupService.getById(id);
        return ResultBean.ok(productGroupPojo);
    }

    @PutMapping(value = "/edit")
    @ResponseBody
    public ResultBean edit(@RequestBody ProductGroupVo productGroupVo){
        ProductGroup productGroup=productGroupService.findById(productGroupVo.getGroupId());
        if(productGroup!=null){
            productGroup.setStatus("2");
            ProductGroup.putTimeAndUser(productGroup);
            productGroupService.save(productGroup);
            productGropMemberService.updateProductIds(productGroupVo.getGroupId(),productGroupVo.getProductIds());
        }
        return ResultBean.ok();
    }

    //TODO  产品组发布和撤回

    /*@PostMapping(value = "/import")
    public ResultBean importProductGroup(MultipartFile file) throws Exception{
        StringBuffer msg = new StringBuffer("导入数据总数->");
        StringBuffer errMessage = new StringBuffer(".错误原因是->");
        AtomicInteger errNum = new AtomicInteger();// 全局错误数
        List<ProductGroupExcelPojo> list=new ArrayList<>();
        try{
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<ProductGroupExcelPojo> dataList=ei.getDataList(ProductGroupExcelPojo.class);
            if (CollectionUtil.isNotEmpty(dataList)) {
                msg.append(dataList.size() + ".错误数据数->");
                dataList.forEach(v -> importData(errMessage, errNum, v, list));
            } else {
                return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
            }
        }catch (Exception e){

        }
    }

    public void importData(StringBuffer errMessage, AtomicInteger errNum, ProductGroupExcelPojo productGroupExcelPojo, List<ProductGroupExcelPojo> list){
        if(productGroupExcelPojo !=null){
            boolean flag = true;
            List<String> messageList = ValidateFilter.getFilterMessage(productGroupExcelPojo, Constants.VALIDATE_DEFAULT);
            flag = checkData(errMessage, errNum, productGroupExcelPojo, flag, messageList);
            if (flag ) {
                list.add(productGroupExcelPojo);
            }
        }
    }

    public boolean checkData(StringBuffer errMessage, AtomicInteger errNum, ProductGroupExcelPojo productGroupExcelPojo, boolean flag, List<String> messageList){

    }*/

    public boolean isRepeat(ProductGroupVo productGroupVo){
        ProductGroup temp=new ProductGroup();
        temp.setGroupName(productGroupVo.getGroupName());
        Optional<ProductGroup> productGroupOpt=productGroupService.findOne(Example.of(temp));
        if(productGroupOpt.isPresent()){
            ProductGroup productGroup=productGroupOpt.get();
            if (productGroupVo.getGroupName() != null && productGroupVo.getGroupName() != productGroup.getGroupName())
                return true;
            else if (productGroupVo.getGroupName() == null)
                return true;
        }
        return false;
    }
}
